{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 解法一：容易超时\n",
    "from typing import List\n",
    "class Solution:\n",
    "    def numDecodings(self, s: str) -> int:\n",
    "        cnt = 0\n",
    "        n = len(s)\n",
    "        def Fun(pos):\n",
    "            cnt = 0\n",
    "            if(pos >= n):\n",
    "                return 1\n",
    "            if(s[pos] != '0'):\n",
    "                cnt = Fun(pos+1)\n",
    "            c_num = int(s[pos:pos+2])\n",
    "            if(c_num > 9 and c_num<= 26 and pos + 1 < n):\n",
    "                cnt += Fun(pos+2)\n",
    "            return cnt\n",
    "        return Fun(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 解法二：动态规划，\n",
    "from typing import List\n",
    "class Solution:\n",
    "    def numDecodings(self, s: str) -> int:\n",
    "        s = \"99\" + s #添加虚拟头部，以便不用对头部做特殊处理\n",
    "        cnt = [0] * len(s)\n",
    "        cnt[0] = cnt[1] = 1\n",
    "        for i in range(2, len(s)):\n",
    "            x = int(s[i-1:i+1])\n",
    "            if( 9 < x and x <= 26): #二位编码不能以0开头\n",
    "                cnt[i] += cnt[i-2]\n",
    "            if(s[i] != '0'):\n",
    "                cnt[i] += cnt[i-1]\n",
    "        return cnt[-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 0]\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "a = Solution()\n",
    "print(a.numDecodings('122'))\n",
    "d = [1,1,1]\n",
    "d[1] = d[2] = 3"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
